package com.snail.billing.page;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.android.util.ResUtil;
import com.snail.billing.DataCache;
import com.snail.billing.Resource;
import com.snail.billing.data.PaymentLogic;
import com.snail.billing.os.DialogPage;
import com.snail.billing.util.WebViewOption;

public class PaymentWebViewPage extends DialogPage implements View.OnClickListener {

	private TextView textTitle;
	private View buttonBack;
	private WebView webView;
	private View buttonBack2;

	private String url;

	private int state;

	@Override
	public int createLayoutId() {
		return ResUtil.getLayoutId(Resource.layout.snailbilling_payment_webview_activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		state = getPageArgs().getInt("state");
		textTitle = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_text));
		textTitle.setText(DataCache.getInstance().paymentParams.platformName);
		buttonBack = findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_button_back));
		buttonBack.setOnClickListener(this);
		//
		//
		webView = (WebView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_webview));
		buttonBack2 = findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_webview_button));
		buttonBack2.setOnClickListener(this);
		buttonBack2.setVisibility(View.GONE);
		//
		WebViewOption.option(webView);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				PaymentWebViewPage.this.url = url;
				if (buttonBack2.getVisibility() == View.GONE) {
					view.loadUrl(url);
				}
				if (isOkUrl(url)) {
					buttonBack2.setVisibility(View.VISIBLE);
				}
				return true;
			}
		});
		DataCache cache = DataCache.getInstance();
		try {
			JSONObject json = new JSONObject(cache.paymentParams.orderResponse);
			String payUrl = json.getString("payUrl");
			String paymentParams = json.getString("paymentParams");
			String post = buildPostString(paymentParams);
			webView.loadUrl(payUrl + "?" + post);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		if (v.equals(buttonBack)) {
			if (isOkUrl(url)) {
				getPageManager().finish();
			} else {
				if (state == PaymentLogic.STATE_IMPREST) {
					getPageManager().backward();
				} else if (state == PaymentLogic.STATE_PAYMENT) {
					getPageManager().finish();
				} else if (state == PaymentLogic.STATE_IMPREST2) {
					getPageManager().backward();
				}
			}
		} else if (v.equals(buttonBack2)) {
			getPageManager().finish();
		}
	}

	private String buildPostString(String json) {
		StringBuilder builder = new StringBuilder();
		try {
			JSONObject obj = new JSONObject(json);
			Iterator<?> iterator = obj.keys();
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				String value = obj.getString(key);
				builder.append(key);
				builder.append("=");
				builder.append(URLEncoder.encode(value, "utf-8"));
				builder.append("&");
			}
			builder.deleteCharAt(builder.length() - 1);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return builder.toString();
	}

	private boolean isOkUrl(String url) {
		Log.i("WebView", "URL=" + url);
		if (url == null) {
			return false;
		}
		try {
			DataCache cache = DataCache.getInstance();
			if (state == PaymentLogic.STATE_IMPREST
			//
					|| state == PaymentLogic.STATE_IMPREST2) {
				if (!url.startsWith("http://")) {
					return false;
				}
				url = url.substring(7);
				url = url.substring(url.indexOf("/"));
				if (url.startsWith("/m/alipay")) {
					return true;
				}
				if (url.startsWith("/m/tenpay")) {
					return true;
				}
			} else if (state == PaymentLogic.STATE_PAYMENT) {
				if (url.startsWith(cache.importParams.fontUrl)) {
					return true;
				}
			}
		} catch (Exception e) {
		}
		return false;
	}

}
